package sysmiddleware

import (
	"fmt"
	"github.com/gin-gonic/gin"
	"github.com/vueadmin/app/admin/internal/svc"
	sys "github.com/vueadmin/app/admin/sys"
	"github.com/vueadmin/app/admin/sys/sysvalidate"
	"github.com/vueadmin/utils"
	"github.com/vueadmin/utils/conv"
	"github.com/vueadmin/utils/response"
)

type CreateMenuMiddleware struct {
	svcCtx *svc.ServiceContext
}

func NewCreateMenuMiddleware(svcCtx *svc.ServiceContext) *CreateMenuMiddleware {
	return &CreateMenuMiddleware{
		svcCtx: svcCtx,
	}
}

// 创建数据表中间件
func (p CreateMenuMiddleware) Handle() gin.HandlerFunc {
	return func(c *gin.Context) {
		var data sys.Menu
		if err := utils.BindAndValid(c, &data); err != nil {
			response.Fail(c, err.Error())
			c.Abort()
			return
		}
		if err := new(sysvalidate.MenuValidate).Validate(&data); err != nil {
			response.Fail(c, err.Error())
			c.Abort()
			return
		}
		if sys.System.GetDBTypeByConnect(data.Connect) != "mysql" {
			return
		}
		prefix := sys.System.GetPrefix(data.Connect)

		if conv.Int(data.CreateTable) > 0 && !conv.IsEmpty(data.Tablename) && !conv.IsEmpty(data.Pk) {
			var sql = fmt.Sprintf(" CREATE TABLE `%s` ( ", prefix+data.Tablename)
			sql += fmt.Sprintf("`%s` int(11) NOT NULL AUTO_INCREMENT ,PRIMARY KEY (`%s`)) ENGINE=InnoDB AUTO_INCREMENT=0 DEFAULT CHARSET=utf8mb4", data.Pk, data.Pk)
			if err := sys.System.Conn(p.svcCtx, data.Connect).Exec(sql).Error; err != nil {
				panic(err)
			}
		}
		if conv.Int(data.PageType) == 2 && conv.Int(data.CreateTable) > 0 {
			var sql = fmt.Sprintf("ALTER TABLE `%s` ADD `name` VARCHAR( 50 ) NOT NULL ,ADD `data` TEXT NOT NULL AFTER `name`", prefix+data.Tablename)

			if err := sys.System.Conn(p.svcCtx, data.Connect).Exec(sql).Error; err != nil {
				panic(err)
			}
		}
		c.Set("data", data)
		c.Next()
	}
}
